import axios from 'axios'
import Utils from '@/common/utils.js'

let location = window.location

const service = function (url, data, method = 'GET', type = 'cs', headers = {}) {
  return new Promise((resolve, reject) => {
    if (type === 'cs') {
      url = process.env.NODE_ENV === 'development' ? `http://${location.host}` + process.env.CS_API + url : process.env.CS_API + url
    } else if (type === 'main') {
      url = process.env.NODE_ENV === 'development' ? `http://${location.host}` + process.env.MAIN_API + url : process.env.MAIN_API + url
    }
    let options = {
      'method': method,
      'url': url,
      'headers': headers && typeof headers === 'object' ? headers : {}
    }
    if (process.env.NODE_ENV === 'production') {
      options.headers['loginServer'] = 'https://api.zy.86edu.net/api/app/person/info'
    } else if (process.env.NODE_ENV === 'test') {
      options.headers['loginServer'] = 'http://api.zytest.86edu.net/api/app/person/info'
    } else {
      options.headers['loginServer'] = 'http://api.zytest.86edu.net/api/app/person/info'
      // options.headers['loginServer'] = 'http://test.zy.api.86edu.net/api/app/person/info'
      // options.headers['loginServer'] = 'http://192.168.50.89:9000/api/app/person/info'
      // options.headers['loginServer'] = 'https://api.zy.86edu.net/api/app/person/info'
    }
    options.headers['X-Requested-Page'] = 'json'
    if (Utils.local('accesstoken')) {
      options.headers['accesstoken'] = Utils.local('accesstoken')
    }
    options[method === 'GET' ? 'params' : 'data'] = data
    axios(options).then((response) => {
      resolve(response.data)
    }).catch((error) => {
      reject(error)
    })
  })
}

export default service
